package com.kx.kxpicture.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.json.JSONUtil;
import com.kx.kxpicture.constant.UserLoginConstant;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.manager.auth.SpaceUserAuthContext;
import com.kx.kxpicture.manager.auth.SpaceUserAuthManager;
import com.kx.kxpicture.manager.auth.StpKit;
import com.kx.kxpicture.manager.auth.model.SpaceUserPermissionConstant;
import com.kx.kxpicture.model.entity.Picture;
import com.kx.kxpicture.model.entity.Space;
import com.kx.kxpicture.model.entity.SpaceUser;
import com.kx.kxpicture.model.entity.User;
import com.kx.kxpicture.model.enums.SpaceRoleEnum;
import com.kx.kxpicture.model.enums.SpaceTypeEnum;
import com.kx.kxpicture.service.PictureService;
import com.kx.kxpicture.service.SpaceService;
import com.kx.kxpicture.service.SpaceUserService;
import com.kx.kxpicture.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 类功能描述
 *
 * @author kuangxin
 * date 2025/9/13
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private UserService userService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    SpaceService spaceService;

    @Resource
    PictureService pictureService;
    @Resource
    SpaceUserService spaceUserService;


    @Override
    public List<String> getRoleList(Object o, String s) {
        return new ArrayList<>();
    }

    private SpaceUserAuthContext getAuthContextByRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String method = request.getMethod(); // 获取请求方法（GET/POST）
        String contentType = request.getHeader(Header.CONTENT_TYPE.getValue());
        SpaceUserAuthContext authRequest;

        if ("POST".equals(method) && ContentType.JSON.getValue().equals(contentType)) {
            // POST + JSON：从body读取
            String body = ServletUtil.getBody(request);
            authRequest = JSONUtil.toBean(body, SpaceUserAuthContext.class);
        } else {
            // GET请求（无论Content-Type）或POST非JSON（如表单）：从paramMap读取
            Map<String, String> paramMap = ServletUtil.getParamMap(request);
            authRequest = BeanUtil.toBean(paramMap, SpaceUserAuthContext.class);
        }
        Long id = authRequest.getId();
        if (ObjUtil.isNotNull(id)) {
            String requestUri = request.getRequestURI();
            String partUri = requestUri.replace(contextPath + "/", "");
            String moduleName = StrUtil.subBefore(partUri, "/", false);
            switch (moduleName) {
                case "picture":
                    authRequest.setPictureId(id);
                    break;
                case "spaceUser":
                    authRequest.setSpaceUserId(id);
                    break;
                case "space":
                    authRequest.setSpaceId(id);
                    break;
                default:
            }
        }
        return authRequest;
    }


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        //判断loginType,仅对类型为"space"进行权限校验
        if (!StpKit.SPACE_TYPE.equals(loginType)) {
            return new ArrayList<>();
        }
        //管理员权限，表示权限校验通过
        List<String> ADMIN_PERMISSIONS = spaceUserAuthManager.getPermissionByRole(SpaceRoleEnum.ADMIN.getValue());
        //获取上下文对象
        SpaceUserAuthContext authContext = getAuthContextByRequest();
        //如果所有字段都为空，表示查询公共图库，可以通过
        if (isAllFieldsNull(authContext)) {
            return ADMIN_PERMISSIONS;
        }
        User loginUser = (User) StpKit.SPACE.getSessionByLoginId(loginId).get(UserLoginConstant.USER_SESSION_KEY);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户未登录");
        }
        Long userId = loginUser.getId();
        SpaceUser spaceUser = authContext.getSpaceUser();
        if (spaceUser != null) {
            return spaceUserAuthManager.getPermissionByRole(spaceUser.getSpaceRole());
        }
        //如果有spaceUserId,必然是团队空间，通过数据库查询SpaceUser对象
        Long spaceUserId = authContext.getSpaceUserId();
        if (spaceUserId != null) {
            //取出当前登录用户的spaceUser
            spaceUser = spaceUserService.getById(spaceUserId);
            if (spaceUser == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到空间用户信息");
            }
            SpaceUser loginSpaceUser = spaceUserService.lambdaQuery()
                    .eq(SpaceUser::getSpaceId, spaceUser.getSpaceId())
                    .eq(SpaceUser::getUserId, userId)
                    .one();
            if (loginSpaceUser == null) {
                return new ArrayList<>();
            }
            //这里会导致管理员在私有空间没有权限，可以再查一次库处理
            return spaceUserAuthManager.getPermissionByRole(loginSpaceUser.getSpaceRole());
        }

        //如果没有spaceUserId,尝试通过spaceId或pictureId获取Space对象并处理
        Long spaceId = authContext.getSpaceId();
        if (spaceId == null) {
            //如果没有spaceId，通过pictureId获取picture对象和space对象
            Long pictureId = authContext.getPictureId();
            //图片id没有，则默认通过权限校验
            if (pictureId == null) {
                return ADMIN_PERMISSIONS;
            }
            Picture picture = pictureService.lambdaQuery()
                    .eq(Picture::getId, pictureId)
                    .select(Picture::getId, Picture::getSpaceId, Picture::getUserId)
                    .one();
            if (picture == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到图片信息");
            }
            spaceId = picture.getSpaceId();
            //公共图库，仅本人或管理员可操作
            if (spaceId == null) {
                if (picture.getUserId().equals(userId) || userService.isAdmin(loginUser)) {
                    return ADMIN_PERMISSIONS;

                } else {
                    //不是自己的图片，仅可查看
                    return Collections.singletonList(SpaceUserPermissionConstant.PICTURE_VIEW);
                }
            }
        }
        //获取space对象
        Space space = spaceService.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到空间信息");
        }
        //根据space类型判断权限
        if (space.getSpaceType() == SpaceTypeEnum.PRIVATE.getValue()) {
            //私有空间，仅本人或管理员有权限
            if (space.getUserId().equals(userId) || userService.isAdmin(loginUser)) {
                return ADMIN_PERMISSIONS;
            } else {
                return new ArrayList<>();
            }
        } else {
            //团队空间，查询spaceuser并获取角色和权限
            spaceUser = spaceUserService.lambdaQuery()
                    .eq(SpaceUser::getSpaceId, spaceId)
                    .eq(SpaceUser::getUserId, userId)
                    .one();
            if (spaceUser == null) {
                return new ArrayList<>();
            }
            return spaceUserAuthManager.getPermissionByRole(spaceUser.getSpaceRole());
        }
    }

    private boolean isAllFieldsNull(Object object) {
        if (object == null) {
            return true;
        }
        return Arrays.stream(ReflectUtil.getFields(object.getClass()))
                .map(field -> ReflectUtil.getFieldValue(object, field))
                .allMatch(ObjectUtil::isEmpty);
    }
}
